/*
 * Copyright (C) 2013 tangzhi
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.tangzsoft.pdmviewer.storage.jdbc;

import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.tangzsoft.pdmviewer.utils.LogFactory;

/**
 *
 * @author tangzhi
 */
public final class DBUtil {
    
    private final static String MYBATIS_CFG = "org/tangzsoft/pdmviewer/mybatis-config.xml" ;
    
    private static SqlSessionFactory sqlSessionFactory = null;
    
    
    public static boolean buildFactory() {
        
        if (sqlSessionFactory!=null) {
            return true;
        }
        
        InputStream inputStream = null;
        
        try {
            String resource = MYBATIS_CFG;
            inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            
        } catch (IOException ex) {
            LogFactory.getLogger(DBUtil.class).error(null, ex);
        } finally {
            try {
                inputStream.close();
            } catch (IOException ex) {
                LogFactory.getLogger(DBUtil.class).error(null, ex);
            }
        }
        
        return sqlSessionFactory != null;
    }
    
    public static SqlSession open() {
        return sqlSessionFactory.openSession();
    }
    
    public static SqlSessionFactory getSessionFactory() {
        return sqlSessionFactory;
    }
}
